/*
 * adc.h
 *
 * adc driver.
 *
 * Copyright (C) 2022 Microwell, Inc.
 * Subject to the GNU Public License, version 2.
 *
 * Author: guoming<guoming@microwell.net>
 */
#include "mcu_regs.h"
#include "types.h"

#ifndef _ADC_H_
#define _ADC_H_

#define IS_EV_CHIP()            ((sys_get_version() & 0x08) != 0)

/*=============================================================================
 *                              Adc config
 *===========================================================================*/


/* AN4/AN5 mode, 0 micro voltage mode, 1 normal mode */
#define CONFIG_ADC_AN4_MODE         (1)
#define CONFIG_ADC_AN5_MODE         (1)

/* AN4/AN5 difference mode enable */
#define CONFIG_ADC_USING_DIFF       (0)

/*
 * Sampling resistance(mOhm) for current measure:
 * Current(mA) = ADC_VAL / 36 / (CONFIG_ADC_SR_MOHM / 1000),
 * ADC_VAL = Current(mA) * CONFIG_ADC_SR_MOHM * 36 / 1000
 */
#define CONFIG_ADC_SR_MOHM          (100)
/*=============================================================================
 *                              Adc config end
 *===========================================================================*/

#if defined(__C51__)
sfr ADCREG1 = 0xF6;
#else
__sfr __at 0xF6 ADCREG1;
#endif

void adc_init(void);
void adc_resume(void);
void adc_exit(void);

/* get vbat in mv */
int16_t adc_get_vbat(void);

/* get ibat (raw value), real_ibat(mA) = ibat_raw * 0.4564  */
int16_t adc_get_ibat_chg_raw(void);

/* get AN2 in mv */
int16_t adc_get_an2(void);
/* get AN3 in mv */
int16_t adc_get_an3(void);

/*
 * get AN4:
 * if CONFIG_ADC_USING_DIFF == 1 or CONFIG_ADC_AN4_MODE == 0, unit is 36*mv
 * if CONFIG_ADC_USING_DIFF == 0 and CONFIG_ADC_AN4_MODE == 1, unit is mv
 */
int16_t adc_get_an4(void);

/*
 * get AN5:
 * if CONFIG_ADC_USING_DIFF == 1 or CONFIG_ADC_AN5_MODE == 0, unit is 36*mv
 * if CONFIG_ADC_USING_DIFF == 0 and CONFIG_ADC_AN5_MODE == 1, unit is mv
 */
int16_t adc_get_an5(void);

/* get AN6 in mv */
int16_t adc_get_an6(void);
/* get AN7 in mv */
int16_t adc_get_an7(void);

int8_t adc_get_offset(void);

#define ADC_SR_MOHM_1000_DIV        (1000 / CONFIG_ADC_SR_MOHM)
#define ADC_CURRENT_MA2VAL(ma)      ((ma) * 36 / ADC_SR_MOHM_1000_DIV)

#endif
